<html>
    <head>
        <title>Customers</title>
        <link href="style.css" rel="stylesheet" type="text/css" media="screen" />
    </head>
    <body>
        <div id="logo">
            <h1><a href="#">Customers</a></h1>
        </div>
        <form>
            <div id='infotab' style='display:none;'>
                <table>
                    <tr>
                        <td>
                        	
                            <input type='button' class='buttons' id='exitbutton' onclick='location.replace("index.html");' value='Exit' />
							<input type='button' class='buttons'  id='searchbutton' onclick='ChangeTab(1);' value='Search' />
							<input type='button' class='buttons'  id='historybutton' onclick='ChangeTab(3);' value='History' />
							<input type='button' class='buttons' id='infobutton' onclick='ChangeTab(0);' value='Info'>
                        </td>
                    </tr>
                </table><input type='hidden' id='customerid' name='customerid'>
                <table class='field'>
                    <tr class='field'>
                        <td class='field'>
                            Name:
                        </td>
                        <td class='field2'>
                            <input type='text' id='firstname' name='firstname'>
                        </td>
                    </tr>
                    <tr class='field'>
                        <td class='field'>
                            Middle:
                        </td>
                        <td class='field2'>
                            <input type='text' id='middlename' name='middlename'>
                        </td>
                    </tr>
                    <tr class='field'>
                        <td class='field'>
                            Last:
                        </td>
                        <td class='field2'>
                            <input type='text' id='lastname' name='lastname'>
                        </td>
                    </tr>
                    <tr class='field'>
                        <td class='field'>
                            Phone:
                        </td>
                        <td class='field2'>
                            <input type='text' id='phone' name='phone'>
                        </td>
                    </tr>
                    <tr class='field'>
                        <td class='field'>
                            Mobile:
                        </td>
                        <td class='field2'>
                            <input type='text' id='mobile' name='mobile'>
                        </td>
                    </tr>
                    <tr class='field'>
                        <td class='field'>
                            Email:
                        </td>
                        <td class='field2'>
                            <input type='text' id='email' name='email'>
                        </td>
                    </tr>
                    <tr class='field'>
                        <td class='field'>
                            Address1:
                        </td>
                        <td class='field2'>
                            <input type='text' id='address1' name='address1'>
                        </td>
                    </tr>
                    <tr class='field'>
                        <td class='field'>
                            Address2:
                        </td>
                        <td class='field2'>
                            <input type='text' id='address2' name='address2'>
                        </td>
                    </tr>
                    <tr class='field'>
                        <td class='field'>
                            City:
                        </td>
                        <td class='field2'>
                            <input type='text' id='city' name='city'>
                        </td>
                    </tr>
                    <tr class='field'>
                        <td class='field'>
                            Zipcode:
                        </td>
                        <td class='field2'>
                            <input type='text' id='zipcode' name='zipcode'>
                        </td>
                    </tr>
                    <tr class='field'>
                        <td class='field'>
                            BirthDate:
                        </td>
                        <td class='field2'>
                            <input type='text' style='width:113px' id='birthdate' name='birthdate'><img src='datechooser.png' onclick='ShowDatePad(document.all.birthdate,0);'>
                        </td>
                    </tr>
                    <tr class='field'>
                        <td class='field'>
                            Balance:
                        </td>
                        <td class='field2'>
                            <input type='text' id='balance' name='balance' onfocus='ShowNumPad(this,0)'>
                        </td>
                    </tr>
                    <tr class='field'>
                        <td class='field'>
                            Credit Limit:
                        </td>
                        <td class='field2'>
                            <input type='text' id='creditlimit' name='creditlimit' onfocus='ShowNumPad(this,0)'>
                        </td>
                    </tr>
                </table>
                <div class='field'>
                    <input type='button' class='buttons' value='Save' onclick='Save();'/><input type='button' class='buttons' value='Delete' onclick='Delete(document.all.customerid.value);'/><input type='button' class='buttons' value='Payment' onclick='ChangeTab(2);'/>
                </div>
                <br/>
            </div>
			
            <div id='searchtab' name='searchtab' style='display:none;'>
                <div class='field'>
                   Search:   <input type='text' id='searcht' name='searcht'>
                </div>
                <div class='field'>
                    <input type='button' class='buttons' value='Search' onclick='Search(document.all.searcht.value,0);'/><input type='button'  class='buttons' value='New' onclick='Load(0);'/><input type='button'  class='buttons'  value='Exit' onclick='location.replace("index.html");'/>
                </div><span id="status">&nbsp;</span>
            </div>
            <div id='historytab' name='historytab' style='display:none;'>
                <table>
                    <tr>
                        <td>
                            <input type='button' class="buttons"  id='exitbutton' onclick='location.replace("index.html");' value='Exit' /><input type='button' class="buttons"  id='searchbutton' onclick='ChangeTab(1);' value='Search' /><input type='button' class="buttons"  id='historybutton' onclick='ChangeTab(3);' value='History' /><input type='button' class="buttons"  id='infobutton' onclick='ChangeTab(0);' value='Info'>
                        </td>
                    </tr>
                </table>
                <div class='field' style=' text-align:center'>
                    History
                </div>
                <div class='field' id='hname' name='hname' style=' text-align:center'>
                    <!--<input type='text' style='width:220px;text-align:center;' id='fullname' name='fullname' value='0.00' readonly/>-->
                </div>
                <div class='field' style='background:#ffcb95;color:#0c2791;'>
                    Balance:<input type='text' id='balancehistory' style='width:120px;' name='balancehistory' value='0.00' readonly/><input type='button' value='Pay' onclick='ChangeTab(2);'>
                </div>
                <div class='field'>
                    Year: <span id='years'></span>
                </div>
                <span id='history' name='history'></span>
            </div>
            <div id='numpad' name='numpad' style='display:none;'>
            </div>
			<div id='datepad' name='datepad' style='display:none;'></div>
            <div id='paytab' name='paytab' style='display:none;'>
			 <table>
                    <tr>
                        <td>
                            <input type='button'  class="buttons" id='exitbutton' onclick='location.replace("index.html");' value='Exit' /><input type='button'  class="buttons" id='searchbutton' onclick='ChangeTab(1);' value='Search' /><input type='button'  class="buttons" id='historybutton' onclick='ChangeTab(3);' value='History' /><input type='button' id='infobutton' class="buttons"   onclick='ChangeTab(0);' value='Info'>
                        </td>
                    </tr>
                </table>
                <div class='field' style=' text-align:center'>
                    Payment on Account
                </div>
                <div class='field' id='fname' name='fname' style=' text-align:center'>
                    <!--<input type='text' style='width:220px;text-align:center;' id='fullname' name='fullname' value='0.00' readonly/>-->
                </div>
                <table class='field'>
                    <tr>
                        <td class='field' style='background:#ffcb95;color:#0c2791;'>
                            Balance:
                        </td>
                        <td>
                            <input type='text' id='balancepay' name='balancepay' value='0.00' readonly/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Date:
                        </td>
                        <td>
                            <input type='text' id='paymentdate' name='paymentdate' style='width:130px' value='' />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <a href=# onclick='ChangePay(document.all.cash,document.all.balancepay.value,true);'>Cash:</a>
                        </td>
                        <td>
                            <input type='text' id='cash' name='cash' value='0.00'  onfocus="ShowNumPad(this,2);"/>
                        </td>
                    </tr>
                    <tr>
                        <td colspan='2'>
                            <input type='button' class='buttons' value='$50' onclick='ChangePay(document.all.cash,50, false);'/><input type='button' class='buttons' value='$20' onclick='ChangePay(document.all.cash,20, false);'/><input type='button' class='buttons' value='$10' onclick='ChangePay(document.all.cash,10, false);'/><input type='button' class='buttons' value='$5' onclick='ChangePay(document.all.cash,5, false);'/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <a href=# onclick='ChangePay(document.all.check,document.all.balancepay.value,true);'>Check:</a>
                        </td>
                        <td>
                            <input type='text' id='check' name='check' value='0.00'  onfocus="ShowNumPad(this,2);"/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <a href=# onclick='ChangePay(document.all.credit,document.all.balancepay.value,true);'>Credit:</a>
                        </td>
                        <td>
                            <input type='text' id='credit' name='credit' value='0.00'  onfocus="ShowNumPad(this,2);"/>
                        </td>
                    </tr>
                    <tr>
                        <td colspan='2'>
                            <input type='button' class='buttons' value='Pay' onclick='MakePayment();'/><input type='button' class='buttons' value='Cancel' onclick='ChangeTab(0);'/>
                        </td>
                    </tr>
                </table>
            </div>
        </form><!-- ====================================== -->
        <!-- End HTML code.  Begin JavaScript code. -->
        <script type="text/javascript" src="gears_init.js">
        </script>
        <script type="text/javascript" src="scripts.js">
        </script>
        <script type="text/javascript">
            
            var db;
            var historyBookmark = 0;
            var searchBookmark = 0;
           
            var CustomerPaymentDBName = 'CustomerPayment_' + currentDate.getFullYear();
            var dbSaleName = "Sale_" + currentDate.getFullYear();
            var dbSaleItemName = "SaleItem_" + currentDate.getFullYear();
			var dbSalePaymentName = "SalePayment_" + currentDate.getFullYear();
			var currentYear = currentDate.getFullYear();
			
            var query = location.search;
            var id = query.substring(query.indexOf("id=") + 3, query.length);
			var search = query.substring(query.indexOf("search=") + 7, query.length);
           // init();
            
            LoadYears2();
            
			 if (id == 'new') {
            
                Load(0);
            }
            else if (id != '' && id != 'reset' && id != 'correct') {
            
                Load(id);
            }
            else {
                document.all.customerid.value = '0';
				if(search ==null)
					search = '';
			    Search(search, 0);
			}
			
			 function LoadYears2(){
                // if (!google.gears.factory || !db) {
                //     alert('Error saving');
                //     return;
                // }
                var yearspan = document.all.years;
                var html = "<select id='yearselect' onchange='ChangeYear()' >"
                // var rs = db.execute("select distinct substr(name, length(name)-3) from sqlite_master where type='table' and  name like '%_20%'");
                var i = new Number(2007);
                var j = new Number(currentDate.getFullYear());
                
                //while (rs.isValidRow()) {
                for (i = 2007; i <= j; i++) {
                    //html += "<option value='" + rs.field(0) + "'";
                    html += "<option value='" + i + "'";
                    //if (rs.field(0) == new Date().getFullYear())
                    if (i == new Date().getFullYear()) 
                        html += " selected ";
                    //html += ">" + rs.field(0) + "</option>";
                    html += ">" + i + "</option>";
                    //rs.next();
                }
                //rs.close();
                html += "</select>";
                yearspan.innerHTML = html;
            }
           
            
            function ChangeYear(){
               // alert(document.all.yearselect.value);
                CustomerPaymentDBName = 'CustomerPayment_' + document.all.yearselect.value;
                dbSaleName = "Sale_" + document.all.yearselect.value;
                dbSaleItemName = "SaleItem_" + document.all.yearselect.value;
				currentYear = document.all.yearselect.value;
                getHistory(0);
            }
			 function DeleteSale(id){
                if (id > 0) {
                
                    var a = confirm('Delete the sale?');
                    if (a != false) {
						
                    	db.execute('delete from '+dbSaleItemName+' where saleid=?', [id]);
						db.execute('delete from '+dbSalePaymentName+' where saleid=?', [id]);
                        db.execute('delete from '+ dbSaleName +' where id=?', [id]);
						alert('Sale deleted!');//
                        //Load first record as default..or display a top 20 search? 
                        //var rs = db.execute('select top 1 id from Product');
                        //rs.close();
                        ChangeTab(3);
                    }
                }
                
            }
			 function DeletePayment(id){
                if (id > 0) {
               // alert(CustomerPaymentDBName);
                  // a =  confirm('Delete the payment?');
				    
                    if ( confirm('Delete the payment?') == true) {
                   
                        db.execute('delete from '+ CustomerPaymentDBName+ ' where id=?;', [id]);
                        alert('Payment deleted!');//
                        //Load first record as default..or display a top 20 search? 
                		ChangeTab(3);      
                    }
                }
                
            }
            
            // Open this page's local database.
            function init(){
                var success = false;
                //alert('Check 1');
                if (window.google && google.gears) {
                    try {
                        db = google.gears.factory.create('beta.database');
                        
                        if (db) {
                            db.open('psdb');
                            if (id == 'reset') {
                                if (confirm('Reset DB?') == true) {
                                    db.execute('drop table if exists Customer');
                                    db.execute('drop table if exists ' + CustomerPaymentDBName);
                                    alert('Done');
                                }
                                
                            }
                            
                            db.execute('create table if not exists Customer' +
                            ' (id int primarykey,' +
                            ' firstname text,' +
                            ' lastname text,' +
                            ' middlename text,' +
                            ' phone text,' +
                            ' phone2 text,' +
                            ' email text,' +
                            ' address1 text,' +
                            ' address2 text,' +
                            ' zipcode text,' +
                            ' city text,' +
                            ' birthdate datetime,' +
                            ' balance real,' +
                            ' creditlimit real' +
                            //' lastpayment text,' +
                            //' lastsale text' +
                            ')');
                            
                            db.execute('create table if not exists ' +
                            CustomerPaymentDBName +
                            ' (id int primarykey,' +
                            ' customerid int,' +
                            ' paymentdate datetime,' +
                            ' paytype text,' +
                            ' amount real' +
                            ')');
                            
                            //create indexes
                            db.execute('create index if not exists Customerix on Customer' +
                            ' (id,firstname,lastname,middlename,phone,phone2,email,city);');
                            db.execute('create index if not exists ' + CustomerPaymentDBName + 'ix on ' + CustomerPaymentDBName +
                            ' (customerid,paymentdate);');
                            
                            success = true;
                            //  alert('Check 3');
                        
                            // Initialize the UI at startup.
                        
                        
                        }
                        
                    } 
                    catch (ex) {
                        setError('Could not create database: ' + ex.message);
                        alert('Could not create database: ' + ex.message);
                    }
                }
                
                
                // Enable or disable UI elements
                
                var inputs = document.forms[0].elements;
                for (var i = 0, el; el = inputs[i]; i++) {
                    el.disabled = !success;
                }
                
            }
            
            function Save(){
                if (!google.gears.factory || !db) {
                    alert('Error saving');
                    return;
                }
                
                // alert('In save');
                var customeridT = document.all.customerid;
                var firstnameT = document.all.firstname;
                var firstname = firstnameT.value;
                //validate required
                if (firstname == '') {
                    alert('Firstname is required');
                    return;
                }
                
                var lastnameT = document.all.lastname;
                var middlenameT = document.all.middlename;
                var phoneT = document.all.phone;
                var phone2T = document.all.mobile;
                var emailT = document.all.email;
                var address1T = document.all.address1;
                var address2T = document.all.address2;
                var cityT = document.all.city;
                var zipcodeT = document.all.zipcode;
                var birthdateT = document.all.birthdate;
                var balanceT = document.all.balance;
                var creditlimitT = document.all.creditlimit;
                
                var customerid = customeridT.value;
                var firstname = firstnameT.value;
                var lastname = lastnameT.value;
                var middlename = middlenameT.value;
                var phone = phoneT.value;
                var phone2 = phone2T.value;
                var email = emailT.value;
                var address1 = address1T.value;
                var address2 = address2T.value;
                var city = cityT.value;
                var zipcode = zipcodeT.value;
                var birthdate = birthdateT.value;
                var balance = balanceT.value;
                var creditlimit = creditlimitT.value;
                
                //check if is new or not
                if (customerid == '0') {
                   // if (option == false) {
                        var rs = db.execute('select max(id)+1 from Customer');
                        customerid = rs.field(0);
                        if (customerid == null) 
                            customerid = 1;
                        rs.close();
                 //   }
                    
                    db.execute('insert into Customer (id, firstname, middlename, lastname, phone, phone2, email, address1, address2, city, zipcode, birthdate, balance, creditlimit) values (? ,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [customerid, firstname, middlename, lastname, phone, phone2, email, address1, address2, city, zipcode, birthdate, balance, creditlimit]);
                    customeridT.value = customerid;
                    //if (option == false) 
                        alert('Customer added.');
						
                }
                else {
                    db.execute('UPDATE Customer SET firstname=?, middlename=?, lastname=?, phone=?, phone2=?, email=?, address1=?, address2=?, city=?, zipcode=?,birthdate=?,balance=?, creditlimit=? WHERE id=?', [firstname, middlename, lastname, phone, phone2, email, address1, address2, city, zipcode, birthdate, balance, creditlimit, customerid]);
                    alert('Customer updated.');
                    
                }
                Load(customerid);
                // Update the UI.
                //elm.value = '';
            
            }
            
            function MakePayment(){
                 
                var customeridT = document.all.customerid.value;
                
                var paymentdate = document.all.paymentdate.value;
                
                var balance = new String();
                balance = document.all.balancepay.value;
                var balanceN = new Number();
                balanceN = balance.replace('$', '').valueOf();
                 
                var cash = document.all.cash.value;
                var check = document.all.check.value;
				var credit = document.all.credit.value;
                if (cash <= 0 & check <= 0 & credit <= 0) {
                    alert('No payment amount');
                    return;
                }
                if (balanceN <= 0) 
                    if (confirm('No balance. Credit to account?') == false) 
                        return;
				if (cash > 0) 
                    SavePayment(customeridT, paymentdate, 'Cash', cash);
				if (credit > 0) 
                    SavePayment(customeridT, paymentdate, 'Credit', credit);
                if (check > 0) 
                    SavePayment(customeridT, paymentdate, 'Check', check);
                if (balanceN <= 0) 
                    alert('Credit added.');
                else 
                    alert('Payment added. Change: ' + formatNumber(balance - cash, true));
                
		document.all.paymentdate.value = StandardDate(currentDate);// + ',' + currentDate.toLocaleTimeString();
                document.all.cash.value = '0.00';
                document.all.check.value = '0.00';
                document.all.credit.value = '0.00';
		
		Load(customeridT);
                ChangeTab(3);
                
                
            }
            
            function SavePayment(customerid, paymentdate, paytype, amount){
                if (!google.gears.factory || !db) {
                    alert('Error saving');
                    return;
                }
                var date = FormatDate(paymentdate);
                // The Gears database automatically escapes/unescapes inserted values.
                var rs = db.execute('select max(id)+1 from ' + CustomerPaymentDBName);
                var newid = rs.field(0);
                if (newid == null) 
                    newid = 1;
				
                db.execute('insert into ' + CustomerPaymentDBName + ' (id, customerid,paymentdate, paytype, amount)  values (? ,?, ?, ?, ?)', [newid, customerid, date, paytype, amount]);
                //update balance
                db.execute('UPDATE Customer SET balance=balance-? WHERE id=?', [amount, customerid]);
                rs.close();
                
                
            }
            
            function DeletePayment2(id){
                if (id > 0) {
                
                    var a = confirm('Delete the payment?');
                    if (a != false) {
                    
                        db.execute('delete from ' + CustomerPaymentDBName + ' where id=?', [id]);
                        alert('Payment deleted!');//
                        //Load first record as default..or display a top 20 search? 
                        ChangeTab(3);
                    }
                }
                
            }
            
            function ChangePay(target, amount, full){
                if (target != null) 
                    target.value = formatNumber(amount, false);
                var cashV = new Number();
                var checkV = new Number();
                var creditV = new Number();
                cashV = document.all.cash.value;
                checkV = document.all.check.value;
                creditV = document.all.credit.value;
                
            }
            
            function ChangeTab(item){
            
				if (item == 8) //datepad
                    document.all.datepad.style.display = 'inline';
                else 
                    document.all.datepad.style.display = 'none';
                if (item == 7) //numpad
                    document.all.numpad.style.display = 'inline';
                else 
                    document.all.numpad.style.display = 'none';
                
                var customeridT = document.all.customerid.value;
                if (item == 2) {
                
                    if (customeridT == 0) {
                        ChangeTab(0);
                        return;
                    }
                    document.all.paytab.style.display = 'inline';
                    
                }
                else 
                    document.all.paytab.style.display = 'none';
                if (item == 0) 
                    document.all.infotab.style.display = 'inline';
                else 
                    document.all.infotab.style.display = 'none';
                if (item == 1) //search
                    document.all.searchtab.style.display = 'inline';
                else 
                    document.all.searchtab.style.display = 'none';
                if (item == 3) //history
                {
                    if (customeridT == 0) {
                        ChangeTab(0);
                        return;
                    }
                    document.all.historytab.style.display = 'inline';
                    getHistory(0);
                }
                else 
                    document.all.historytab.style.display = 'none';
            }
            
            function Delete(id){
                if (id > 0) {
                
                    var a = confirm('Delete the customer?');
                    if (a != false) {
                    
                        db.execute('delete from customer where  id='+ id);
                        alert('Customer deleted!');//
                        //Load first record as default..or display a top 20 search? 
                        
                        Search('', 0);
                    }
                }
                
            }
            
            function Search(search, option){
                try {
					
					ChangeTab(1);
					
					searchBookmark = searchBookmark + option;
					if (searchBookmark < 0) 
						searchBookmark = 0;
					var s = new String(search);
					
					var query = 'select * from Customer where ';
					
				if (s.indexOf(' ') > 0) {
						s = s.split(' ');
						
						query += ' (firstname like "%' + s[0] + '%"';
						query += ' AND lastname like "%' + s[1] + '%") OR';
					}
					//else {
						query += ' firstname like "%' + search + '%"';
						query += ' OR lastname like "%' + search + '%"';
				//	}
					query += ' OR middlename like "%' + search + '%"';
					query += ' OR phone like "%' + search + '%"';
					query += ' OR email like "%' + search + '%"';
					query += ' OR city like "' + search + '%"';
					query += ' OR zipcode like "' + search + '%"';
					query += ' OR address1 like "%' + search + '%"';
					query += ' OR address2 like "%' + search + '%"';
					query += ' ORDER BY firstname, lastname asc limit 10 offset ' + searchBookmark;
					
					var status = document.all.status;
					//status.innerHTML =query;
					//return;
					status.innerHTML = '<div class="field" >Search Results:</div>';//'Searching...' ;
					var rs = db.execute(query);
					var html = "";
					var count = new Number(0);
					while (rs.isValidRow()) {
					
						html += SearchResult(rs.field(0), getFullName(rs.field(1), rs.field(2), rs.field(3)), 'Tel:' + rs.field(4), 'Bal: ' + formatNumber(rs.field(12), true));
						count++;
						rs.next();
					}
					
					if (searchBookmark >= 10) 
						html += "<a href=# onclick='Search(\"" + search + "\",-10);'>[Back]</a>";
					if (count >= 10) 
						html += "<a href=# onclick='Search(\"" + search + "\",10);'>[Next]</a>";
					
						status.innerHTML = html;
					rs.close();
				} 
				catch (ex) {
					status.innerHTML = 'No records found';
					alert(ex);
				}
                
            }
            
            function Load(id){
                //alert('Loading...');
                var status = document.all.status;
                status.innerHTML = '';
                // alert(id);
                var customeridT = document.all.customerid;
                var firstnameT = document.all.firstname;
                var lastnameT = document.all.lastname;
                var middlenameT = document.all.middlename;
                var phoneT = document.all.phone;
                var phone2T = document.all.mobile;
                var emailT = document.all.email;
                var address1T = document.all.address1;
                var address2T = document.all.address2;
                var cityT = document.all.city;
                var zipcodeT = document.all.zipcode;
                var birthdateT = document.all.birthdate;
                var balanceT = document.all.balance;
                var balancePayT = document.all.balancepay;
                var balanceHistoryT = document.all.balancehistory;
                var creditlimitT = document.all.creditlimit;
                
                customeridT.value = id;
                if (id > 0) {
                    var rs = db.execute('select * from Customer where id=' + id);
                    firstnameT.value = rs.field(1);
                    lastnameT.value = rs.field(2);
                    middlenameT.value = rs.field(3);
                    document.all.fname.innerHTML = getFullName(firstnameT.value, middlenameT.value, lastnameT.value);
                    document.all.hname.innerHTML = document.all.fname.innerHTML
                    phoneT.value = rs.field(4);
                    phone2T.value = rs.field(5);
                    emailT.value = rs.field(6);
                    address1T.value = rs.field(7);
                    address2T.value = rs.field(8);
                    cityT.value = rs.field(10);
                    zipcodeT.value = rs.field(9);
                    birthdateT.value = rs.field(11);
                    balanceT.value = formatNumber(rs.field(12), false);
                    balancePayT.value = formatNumber(balanceT.value, true);
                    balanceHistoryT.value = formatNumber(balanceT.value, true);
                    creditlimitT.value = formatNumber(rs.field(13), false);
                    rs.close();
                }
                else {
                    firstnameT.value = '';
                    lastnameT.value = '';
                    middlenameT.value = '';
                    phoneT.value = '';
                    phone2T.value = '';
                    emailT.value = '';
                    address1T.value = '';
                    address2T.value = '';
                    cityT.value = '';
                    zipcodeT.value = '';
                    birthdateT.value = '';
                    balanceT.value = '0.00';
                    creditlimitT.value = '100.00';
                }
		document.all.paymentdate.value = StandardDate(currentDate);// + ',' + currentDate.toLocaleTimeString();
                document.all.cash.value = '0.00';
                document.all.check.value = '0.00';
                document.all.credit.value = '0.00';
		ChangeTab(2);
                
            }
            
            //loads/imports xml data
            function LoadX(id){
                //document.all.info.style.display = 'inline';
                //TODO:
                // catch on blank, maybe set a pause/sets on for loop
                var customerid = "";
                var firstname = "";
                var lastname = "";
                var middlename = "";
                var phone = "";
                var phone2 = "";
                var email = "";
                var address1 = "";
                var address2 = "";
                var city = "";
                var zipcode = "";
                var birthdate = "";
                var balance = "";
                var creditlimit = "";
                
                //var xmlDoc = new  Document();
                if (window.XMLHttpRequest) {
                    xhttp = new XMLHttpRequest()
                }
                else {
                    xhttp = new ActiveXObject("Microsoft.XMLHTTP")
                }
                xhttp.open("GET", "customers.xml", false);
                xhttp.send("");
                xmlDoc = xhttp.responseXML;
                
                var y = xmlDoc.getElementsByTagName("customers");
                var i = new Number();
                i = 0;
                for (i = 0; i < y.length; i++) {
                    /// x = y[i].childNodes; //a specific customer
                    // if (x[1].childNodes[0].nodeValue == id || id == 0) //check if matches an id
                    //{
                    customerid = y[i].childNodes[1].childNodes[0].nodeValue;
                    firstname = y[i].childNodes[3].childNodes[0].nodeValue;
                    try {
                        lastname = y[i].childNodes[7].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        lastname = "";
                    }
                    try {
                        middlename = y[i].childNodes[5].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        middlename = "";
                    }
                    try {
                        phone = y[i].childNodes[11].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        phone = "";
                    }
                    try {
                        phone2 = y[i].childNodes[13].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        phone2 = "";
                    }
                    try {
                        email = y[i].childNodes[15].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        email = "";
                    }
                    try {
                        address1 = y[i].childNodes[17].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        address1 = "";
                    }
                    try {
                        address2 = y[i].childNodes[19].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        address2 = "";
                    }
                    try {
                        zipcode = y[i].childNodes[21].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        zipcode = "";
                    }
                    if (zipcode != '') 
                        city = LoadCity(y[i].childNodes[21].childNodes[0].nodeValue);
                    else 
                        city = "";
                    birthdate = "";
                    try {
                        balance = y[i].childNodes[27].childNodes[0].nodeValue;
                    } 
                    catch (ex) {
                        balance = "0.00";
                    }
                    creditlimit = '100.00';//default value
                    birthdate = '';
                    
                    db.execute('insert into Customer (id, firstname, middlename, lastname, phone, phone2, email, address1, address2, city, zipcode, birthdate, balance, creditlimit) values (? ,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [customerid, firstname, middlename, lastname, phone, phone2, email, address1, address2, city, zipcode, birthdate, balance, creditlimit]);
                    document.all.status.innerHTML = "Status: " + i + "/" + y.length;
                    
                }
                
            }
            
            //loads/imports xml data
            function LoadCity(zipcode){
                if (window.XMLHttpRequest) {
                    xhttp = new XMLHttpRequest()
                }
                else {
                    xhttp = new ActiveXObject("Microsoft.XMLHTTP")
                }
                
                xhttp.open("GET", "cities.xml", false);
                xhttp.send("");
                xmlDoc = xhttp.responseXML;
                
                var y = xmlDoc.getElementsByTagName("cities");
                for (i = 0; i < y.length; i++) {
                    x = y[i].childNodes; //a specific city
                    if (x[1].childNodes[0].nodeValue == zipcode) //check if matches an id
                    {
                        return x[3].childNodes[0].nodeValue;
                    }
                }
            }
            
            function getHistory(option){
                var customerid = document.all.customerid.value;
                var history = document.all.history;
                var html = "";// "<table border='1'>";
               // alert(CustomerPaymentDBName);
                //row count control
                historyBookmark = historyBookmark + option;
                if (historyBookmark < 0) 
                    historyBookmark = 0;
                
                //get sales
                var query = "select distinct date(saledate) as tdate, 0 as ttype, saleid, 'nopayment' as paytype, sum((qty*price)+taxes) as total";
                query += " from " + dbSaleName + " inner join " + dbSaleItemName + " on " + dbSaleName + ".id=saleid ";
                query += " where customerid=" + customerid
                query += " group by saledate," + dbSaleName + ".id ";
                
                //get payments 
                query += " union select distinct date(paymentdate) as tdate, 1 as ttype, id, paytype, amount as total";
                query += " from " + CustomerPaymentDBName;
                query += " where customerid=" + customerid;
                query += " order by 1 desc";
                //row control
                query += " limit 10 offset " + historyBookmark;
                
                query = "select distinct date(saledate) as tdate, 0 as ttype, s.id, 'nopayment' as paytype, sum((qty*price)+taxes) as total from ";
                query += dbSaleName + " s inner join " + dbSaleItemName + " on s.id=saleid where customerid=" + customerid + " group by saledate,s.id ";
                query += "union select distinct date(paymentdate) as tdate, 1 as ttype, id, paytype, amount as total from ";
                query += CustomerPaymentDBName + " where customerid=" + customerid + " order by 1 desc limit 10 offset " + historyBookmark + ";";
                
                
                //alert(historyBookmark);
                
                try {
                    var rs = db.execute(query);
                } 
                catch (ex) {
                    history.innerHTML = "No results";
                    return;
                }
                var count = 0;
                
                while (rs.isValidRow()) {
                
                    var type = '';
                    var info = '';
                    if (rs.field(1) == 1) {
                        type = 'Payment  <a href="#" onclick="DeletePayment('+ rs.field(2) +')">(delete)</a>';
                        info = rs.field(3);
                    }
                    else {
                          type = 'Sale <a href="#" onclick="DeleteSale('+ rs.field(2) +')">(delete)</a>';
                        info = "<a href='saleview.html?id=" + rs.field(2) + "&year="+ currentYear +"'>[View]</a>";
                    }
                    var date = new Date(rs.field(0));
                    var days = ['Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab'];
                    //+ ": " + days[date.getDay()]
                    html += SearchResult2(formatNumber(rs.field(4), true), rs.field(0), type, '', info);
                    
                    /*if (count % 2 == 0) 
                     html += "<tr><td class='itemtd' style='width:50px'>" + rs.field(0) + "</td><td class='itemtd' >" + type + "</td><td class='itemtd' >"+info+"</td><td class='itemtd' >" + formatNumber(rs.field(3),true)  + "</td></tr>";
                     else
                     html += "<tr><td class='itemtdpar' style='width:50px'>" + rs.field(0) + "</td><td class='itemtdpar' >" + type + "</td><td class='itemtdpar' >"+info+"</td><td class='itemtdpar' >" + formatNumber(rs.field(3),true)  + "</td></tr>";
                     */
                    count++;
                    rs.next();
                }
                
                if (historyBookmark >= 10) 
                    html += "<a href=# onclick='getHistory(-10);'>[Back 10]</a>";
                if (count >= 10) 
                    html += "<a href=# onclick='getHistory(10);'>[Next 10]</a>";
                
                history.innerHTML = html;
                //history.innerHTML = query;
                
                rs.close();
                
            }
        </script>
    </body>
</html>
